﻿$(function () {
    $("#optRemovablePartialProsthesisDesign").attr("class", "HoverOnList");
    $("#breadcrumb").append('<li><a href="' + $("#urlRemovablePartialProsthesisDesign").val() + '" title="Diseño de Prótesis Parcial Removible">Diseño de Prótesis Parcial Removible</a></li>');

    $.datepicker.regional['es'] = {
        closeText: 'Cerrar',
        prevText: '<Ant',
        nextText: 'Sig>',
        currentText: 'Hoy',
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
        dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['es']);

    $("#txtStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    var validator1 = $("#frmPrintable").bind("invalid-form.validate", function () {
        //$("#lblError").show();
    }).validate({
        debug: true,
        rules: {
            txtPersonFilter: {
                required: true,
                minlength: 1
            },
            classification: {
                required: true,
                minlength: 1
            },
            connector: {
                required: true,
                minlength: 1
            },
            baseType: {
                required: true,
                minlength: 1
            },
            backColor: {
                required: true,
                minlength: 1
            },
            frontColor: {
                required: true,
                minlength: 1
            },
        },
        messages: {
            txtPersonFilter: "La persona es requerida",
            classification: "La clasificación es requerida",
            connector: "El conector es requerido",
            baseType: "El tipo de base es requerido",
            backColor: "El color anterior es requerido",
            frontColor: "El color posterior es requerido"
        }
    });

    var validator2 = $("#frmDetails").bind("invalid-form.validate", function () {
        //$("#lblError").show();
    }).validate({
        debug: true,
        rules: {
            cmbType: 'required',
            toothID: 'required',
            txtType: {
                required: true,
                minlength: 1
            },
            txtIndirectRetainer: {
                required: true,
                minlength: 1
            },
        },
        messages: {
            cmbType: "El tipo es requerido",
            toothID: "El diente es requerido",
            txtType: "El tipo es requerido",
            txtIndirectRetainer: "El retenedor indirecto es requerido"
        }
    });

    $('.item-del').live('click', function () {
        if (confirm('¿Esta seguro que desea eliminar el registro?')) {
            $(this).closest('li').remove();
        }
    });

    $('#menuClear').click(function () {
        ClearForm();
    });

    $('#btnClear').click(function () {
        ClearForm();
    });

    $('#btnClearForm').click(function () {
        Clear();
    });

    $('#btnAdd').click(function () {
        AddRecord();
    });

    $('#btnSaveMenu').click(function () {
        if ($("#frmPrintable").valid()) {
            if (parseInt($('#personID').val()) > 0) {
                Add();
            }
            else {
                alert('Debe seleccionar un paciente.');
            }
        }
    });

    $('#btnSave').click(function () {
        if ($("#frmPrintable").valid()) {
            if (parseInt($('#personID').val()) > 0) {
                Add();
            }
            else {
                alert('Debe seleccionar un paciente.');
            }
        }
    });

    $('#btnUpdateMenu').click(function () {
        if ($("#frmPrintable").valid()) {
            Edit();
        }
    });

    $('#btnUpdate').click(function () {
        if ($("#frmPrintable").valid()) {
            Edit();
        }
    });

    $('#btnPrintMenu').click(function () {
        if ($("#frmPrintable").valid()) {
            Print();
        }
    });

    $('#btnPrint').click(function () {
        if ($("#frmPrintable").valid()) {
            Print();
        }
    });

    $('#btnSearch').click(function () {
        Search();
    });

    if (!(typeof $('#txtPersonFilter')[0] === "undefined")) {
        InitAutocomplete();
    }

    $('#txtBackColor, #txtFrontColor').ColorPicker({
        onSubmit: function (hsb, hex, rgb, el) {
            $(el).val(hex);
            $(el).ColorPickerHide();
        },
        onBeforeShow: function () {
            $(this).ColorPickerSetColor(this.value);
        }
    }).bind('keyup', function () {
    $(this).ColorPickerSetColor(this.value);
});

});

function AddRecord() {

    if ($("#frmDetails").valid()) {
        var item = "<li toothID='" + $('#cmbTeeth').val() + "' rdbType='" + $('#cmbType').val() + "' txtType='" + $('#txtType').val() + "' txtIndirectRetainer='" + $("#txtIndirectRetainer").val() + "'>" +
                    "<table style='width: 100%;'>" +
                        "<tr>" +
                            "<td style='width: 20%; text-align: left;'>" + $("#cmbTeeth option:selected").text() + "</td>" +
                            "<td style='width: 23%; text-align: left;'>" + $("#cmbType option:selected").text() + "</td>" +
                            "<td style='width: 31%; text-align: left;'>" + $('#txtType').val() + "</td>" +
                            "<td>" + $('#txtIndirectRetainer').val() + "</td>" +
                        "</tr>" +
                    "</table>" +
                    "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                "</li>";
        $("#printableList ul").append(item);
        Clear();
    }
}

function ClearForm() {
    Clear();

    var $radios = $('input:radio[name=model]');
    $radios.filter('[value=true]').attr('checked', true);

    $('#txtClassification').val('');
    $('#txtConnector').val('');
    $('#txtBaseType').val('');

    $("#txtClassification").removeClass("error");
    $("#txtConnector").removeClass("error");
    $("#txtBaseType").removeClass("error");

    $("#frmPrintable").find(".error").remove();
}

function Clear() {
    var cmbTeeth = $('#cmbTeeth');
    cmbTeeth[0].selectedIndex = 0;

    var $radios = $('input:radio[name=rdbType]');
    $radios.filter('[value=principal]').attr('checked', true);

    $('#txtType').val('');
    $('#txtIndirectRetainer').val('');

    $("#txtType").removeClass("error");
    $("#txtIndirectRetainer").removeClass("error");
    $("#cmbTeeth").removeClass("error");

    $("#frmDetails").find(".error").remove();
}

function ConfirmDelete(id) {
    if (confirm('¿Esta seguro que desea eliminar el registro?')) {
        Delete(id);
    }
}

function Add() {
    var list = new Array();
    $('#lstPrintableList li').each(function () {
        var current = $(this);
        var item = current.attr("toothID") + ";" + current.attr("rdbType") + ";" + current.attr("txtType") + ";" + current.attr("txtIndirectRetainer") + ";";
        list.push(item);
    });
    debugger;
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlCreate").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                partyID: $('#personID').val(),
                model: $("#rdbTop").attr("checked") == 'checked' ? "true" : "false",
                classification: $('#txtClassification').val(),
                connector: $('#txtConnector').val(),
                baseType: $('#txtBaseType').val(),
                backColor: $('#txtBackColor').val(),
                frontColor: $('#txtFrontColor').val(),
                comments: $('#txtComments').val(),
                items: list,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlPrint").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function Edit() {
    var list = new Array();
    $('#lstPrintableList li').each(function () {
        var current = $(this);
        var item = current.attr("toothID") + ";" + current.attr("rdbType") + ";" + current.attr("txtType") + ";" + current.attr("txtIndirectRetainer") + ";";
        list.push(item);
    });

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlEdit").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                Address: $('#address').val(),
                Phone: $('#phone').val(),
                CompanyName: $('#companyName').val(),
                Logo: $('#logo').val(),
                MedicName: $('#txtMedicName').val(),
                MedicIdentification: $('#txtMedicIdentification').val(),
                PatientName: $('#txtPatientName').val(),
                PatientIdentification: $('#txtPatientIdentification').val(),
                removablePartialProsthesisDesignID: $('#reportID').val(),
                partyID: $('#partyID').val(),
                companyID: $('#companyID').val(),
                createdBy: $('#createdBy').val(),
                model: $("#rdbTop").attr("checked") == 'checked' ? "true" : "false",
                classification: $('#txtClassification').val(),
                connector: $('#txtConnector').val(),
                baseType: $('#txtBaseType').val(),
                backColor: $('#txtBackColor').val(),
                frontColor: $('#txtFrontColor').val(),
                comments: $('#txtComments').val(),
                items: list,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=4";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function Print() {
    var list = new Array();
    $('#lstPrintableList li').each(function () {
        var current = $(this);
        var item = current.attr("toothID") + ";" + current.attr("rdbType") + ";" + current.attr("txtType") + ";" + current.attr("txtIndirectRetainer") + ";";
        list.push(item);
    });
    debugger;
    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlPrint").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                Address: $('#address').val(),
                Phone: $('#phone').val(),
                CompanyName: $('#companyName').val(),
                Logo: $('#logo').val(),
                MedicName: $('#txtMedicName').val(),
                MedicIdentification: $('#txtMedicIdentification').val(),
                PatientName: $('#txtPatientName').val(),
                PatientIdentification: $('#txtPatientIdentification').val(),
                removablePartialProsthesisDesignID: $('#reportID').val(),
                partyID: $('#partyID').val(),
                companyID: $('#companyID').val(),
                createdBy: $('#createdBy').val(),
                model: $("#rdbTop").attr("checked") == 'checked' ? "true" : "false",
                classification: $('#txtClassification').val(),
                connector: $('#txtConnector').val(),
                baseType: $('#txtBaseType').val(),
                backColor: $('#txtBackColor').val(),
                frontColor: $('#txtFrontColor').val(),
                comments: $('#txtComments').val(),
                items: list,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=1";
                window.location = $("#urlPrint").val(); //$("#urlIndex").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function Delete(objectId) {
    $.ajax(
    {
        type: "POST",
        url: $('#urlDelete').val(),
        data:
            JSON.stringify({
                id: objectId
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlIndex").val();
                 window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=1";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = $("#urlIndex").val();
            window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function InitAutocomplete() {
    $("#txtPersonFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetPatients').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.name + " " + item.firstName + " " + item.lastName + ". ID: " + item.identification,
                            ID: item.personID,
                            Name: item.name,
                            FirstName: item.firstName,
                            LastName: item.lastName,
                            Identification: item.identification,
                            DefaultPhone: item.defaultPhone
                        }
                    }));
                },
                error: function (data, status, e) {
                  
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $('#personID').val(ui.item.ID);
        }
    });

    $("#txtPersonFilter").keyup(function () {
        if (!this.value) {
            $('#personID').val();
        }
    });
}

function Search() {
    debugger;
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
    var date2 = null;

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                createdBy: $('#cmbMedic').val(),
                startDate: date1,
                endDate: date2,
                isByName: $('#rdbNameFilter').is(':checked'),
                personFilter: $('#txtPersonFilter').val(),
                partyID: $('#personID').val(),
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            debugger;
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}